import Axios from 'axios';
import qs from 'qs';
import store from '../store';
// 添加请求拦截器
const instance = Axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 1000 * 10,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    Accept: 'application/json'
  }
});
// http request 拦截器
instance.interceptors.request.use(
  async config => {
    let { token = '' } = store.state;
    if (token) {
      config.headers['authToken'] = token;
    }
    if (config.method.toLowerCase() === 'post') {
      if (config.data && config.data.json) {
        config.headers['Content-Type'] = 'application/json; charset=UTF-8';
        delete config.data.json;
      } else {
        config.data = qs.stringify(config.data);
      }
    }
    if (config.params || config.method.toLowerCase() === 'get') {
      config.params = Object.assign(config.data || {}, config.params || {});
      delete config['data'];
    }
    return config;
  },
  err => {
    alert('请求失败' + err.message);
    return Promise.reject(err);
  }
);

instance.interceptors.response.use(
  response => {
    if (response.data.code === 20001) {
      localStorage.removeItem('token');
      localStorage.removeItem('openId');
      location.href = location.origin + process.env.VUE_APP_PUBLIC_PATH;
      return;
    }
    if (response.headers.authtoken) {
      localStorage.setItem('token', response.headers.authtoken);
      store.commit('setToken', response.headers.authtoken);
    }

    // if (response.data.code === 200) {
    //   console.table(`%c url:${response.config.url}`, 'background-color:#1DA1F2;color:#fff', response.data.data);
    // } else {
    //   console.error(`%c url:${response.config.url}`, 'background-color:#1DA1F2;color:#fff', response.data);
    // }
    return response.data;
  },
  err => {
    return Promise.reject(err);
  }
);

export default instance;
